<template>
  <div class="avatar-container">
    <m-header title="设置头像"></m-header>
    <div class="avatarlists">
      <div class="avatarItem" v-for="(item, index) in avatarsList"
        :key="index" @click="handleAvatar(item)">
        <img :src="item.avatar_url" alt="">
        <span class="on" v-if="item.avatar_url===selectVal"></span>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  name: 'Avatar',
  data () {
    return {
      selectVal: '',
      avatarsList: []
    };
  },
  computed: {
    ...mapGetters({
      userInfo: 'mine/userInfo'
    })
  },
  mounted () {
    if (this.userInfo.avatar) {
      this.selectVal = this.userInfo.avatar;
    } else {
      this.getUseInfo();
    }
    this.getAvatarsList();
  },
  methods: {
    ...mapActions({
      getMineInfo: 'mine/mineInfo',
      getAvatars: 'common/getAvatars',
      setMemberInfo: 'common/setMemberInfo'
    }),
    handleAvatar (item) {
      this.selectVal = item.avatar_url;
      const params = {
        // nickname: this.userInfo.nicknae,
        avatar: item.avatar_url
      }
      this.setMemberInfo(params).then(res => {
        // localStorage.removeItem('userInfo');
      })
    },
    getAvatarsList () {
      this.getAvatars().then(res => {
        if (res.length) {
          this.avatarsList = res;
        }
      });
    },
    getUseInfo () {
      this.getMineInfo().then(res => {
        this.selectVal = res.avatar;
      });
    }
  }
};
</script>

<style lang="less">
  .avatar-container {
    padding-top: 0.92rem;
    .avatarlists {
      display: inline-flex;
      flex-wrap: wrap;
      justify-content: space-between;
      margin: 0.4rem 0.6rem;
      &::after {
        content: '';
        display: block;
        width: 1.6rem;
      }
      .avatarItem {
        position: relative;
        width: 1.6rem;
        height: 1.6rem;
        margin-bottom: 0.6rem;
        overflow: hidden;
        img {
          display: block;
          width: 100%;
          height: 100%;
        }
        .on {
          position: absolute;
          bottom: 0;
          right: 0.17rem;
          width: 0.36rem;
          height: 0.36rem;
          background-size: 0.36rem 0.36rem;
          background-repeat: no-repeat;
          background-image: url('../../../assets/imgs/mine/icon-select@2x.png');
        }
      }
    }
  }
</style>
